package com.tongjie.hotelbooking.security.entrypoint;

import com.alibaba.fastjson.JSON;
import com.tongjie.hotelbooking.http.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Slf4j
public class ResponseBodyEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.error("", authException);
        if (authException instanceof InsufficientAuthenticationException) {
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/json; charset=utf-8");

            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(BaseResponse.builder().code(response.getStatus()).message("UNAUTHORIZED").build()));
        } else {
            log.error("", authException);
            response.setStatus(HttpStatus.FORBIDDEN.value());
        }
    }
}
